package com.couldtest.Filter;


import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import org.omg.PortableServer.SERVANT_RETENTION_POLICY_ID;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SERVLET_DETECTION_FILTER_ORDER;

public class RateLimitFilter extends ZuulFilter {

    //每秒创建的令牌数量
    private static final RateLimiter RATE_LIMITER = RateLimiter.create(100);

    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        //限流的过滤器优先级要设为最高
        return SERVLET_DETECTION_FILTER_ORDER-1;
    }

    @Override
    public boolean shouldFilter() {
        return false;
    }

    @Override
    public Object run() {
        //取令牌
        if(!RATE_LIMITER.tryAcquire()){
            throw  new RuntimeException("服务器繁忙清稍后再试");
        }
        return null;
    }
}
